/* Copyright 2014 Nate Eisner, Noah Bahr
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package edu.uwp.kcwm;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Exhibit extends Activity {
	// Possible Buttons
	Button btnNext, btnBack, btnInfo, btnPics, btnVideo, btnArtifacts = null;

	String exhibitNum;
	private Bitmap bitmap;
	private ImageView imgV;
	WebView webV;

	// for content loading
	private ProgressDialog pDialog;
	// URL for webserver
	private static final String SITEURL = "http://gracefullyengineered.com/kcwm/";

	/**
	 * Runs when activity is created
	 * Checks for information, pictures, video, artifacts
	 *  then creates buttons and click listeners for found
	 *  data.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exhibit);
		imgV = (ImageView) findViewById(R.id.exhibitImageView);
		pDialog = new ProgressDialog(this);

		// get exhibit number
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			exhibitNum = extras.getString("exhibitNum");
		}
		getActionBar().setTitle("Exhibit " + exhibitNum);

		// set exhibit image
		new LoadImg().execute(SITEURL + exhibitNum + "/exhibit.jpg");
		imgV = (ImageView) findViewById(R.id.exhibitImageView);

		// Exhibit 1 & 7 are special
		if (exhibitNum.equals("1") || exhibitNum.equals("7")) {
			Button info = (Button) findViewById(R.id.exhibitInfoButton);
			info.setVisibility(View.GONE);
			webV = (WebView) findViewById(R.id.exhibitWebView);
			webV.setVisibility(View.VISIBLE);
			webV.loadUrl(SITEURL + exhibitNum + "/info.html");
		} else {
			// if there is info then show button
			checkInfoURL();
			// if pics then show button
			checkPicsURL();
			// if video then show button
			checkVideoURL();
			// if artifacts then show button
			checkArtifactsURL();
		}
	}

	/**
	 * On click of the back button, this will go to the next exhibit bassed off
	 * of the current exhibit number exception for exhibit 1
	 * 
	 * @param view
	 */
	public void setBackButton(View view) {
		btnBack = (Button) findViewById(R.id.exhibitBackButton);
		if (exhibitNum.equals("1")) {
			finish();
		}
		for (int i = 2; i <= 10; i++) {
			Integer bigI = i;
			if (exhibitNum.equals(bigI.toString())) {
				Intent intent = new Intent(Exhibit.this, Exhibit.class);
				bigI--;
				intent.putExtra("exhibitNum", bigI.toString());
				Exhibit.this.startActivity(intent);
				finish();
			}
		}
	}

	/**
	 * On click of the next button, this will go to the next exhibit based off
	 * of the current exhibit number exception for exhibit 10
	 * 
	 * @param view
	 */
	public void setNextButton(View view) {
		btnNext = (Button) findViewById(R.id.exhibitNextButton);
		for (int i = 1; i < 10; i++) {
			Integer bigI = i;
			if (exhibitNum.equals(bigI.toString())) {
				Intent intent = new Intent(Exhibit.this, Exhibit.class);
				bigI++;
				intent.putExtra("exhibitNum", bigI.toString());
				Exhibit.this.startActivity(intent);
				finish();
			}
		}
		if (exhibitNum.equals("10")) {
			finish();
		}
	}

	/**
	 * Goes to pictures activity
	 * 
	 * @param view
	 */
	public void gotoPics(View view) {
		Intent intent = new Intent(Exhibit.this, Pics.class);
		intent.putExtra("exhibitNum", exhibitNum);
		Exhibit.this.startActivity(intent);
	}

	/**
	 * Goes to video activity
	 * @param view
	 */
	public void gotoVideo(View view) {
		Intent intent = new Intent(Exhibit.this, ExhibitVideo.class);
		intent.putExtra("exhibitNum", exhibitNum);
		Exhibit.this.startActivity(intent);
	}

	/**
	 * Goes to information activity
	 * 
	 * @param view
	 */
	public void gotoInfo(View view) {
		Intent intent = new Intent(Exhibit.this, Info.class);
		intent.putExtra("exhibitNum", exhibitNum);
		Exhibit.this.startActivity(intent);
	}

	/**
	 * Goes to Artifacts activity
	 * 
	 * @param view
	 */
	public void gotoArtifacts(View view) {
		Intent intent = new Intent(Exhibit.this, ExhibitArtifacts.class);
		intent.putExtra("exhibitNum", exhibitNum);
		Exhibit.this.startActivity(intent);
	}

	/**
	 * AsyncTask that is used to load an image from a given URL
	 * 
	 * @author Nate Loads in a string as the URL and returns a Bitmap
	 */
	class LoadImg extends AsyncTask<String, Void, Bitmap> {
		protected void onPreExecute() {
			pDialog.setMessage("Loading Exhibit " + exhibitNum + " content...");
			pDialog.show();
		}

		/**
		 * Loads bitmap from url
		 */
		@Override
		protected Bitmap doInBackground(String... urls) {
			try {
				bitmap = BitmapFactory.decodeStream((InputStream) new URL(
						urls[0]).getContent());
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return bitmap;
		}

		/**
		 * Sets bitmap to imageview if exists
		 */
		@Override
		protected void onPostExecute(Bitmap result) {

			if (result != null) {
				imgV.setImageBitmap(result);
			} else {
				Toast.makeText(Exhibit.this,
						"Image does not exist or Network Error",
						Toast.LENGTH_SHORT).show();
			}
			SystemClock.sleep(700);
			pDialog.dismiss();
		}
	}

	/**
	 * when activity resumes
	 */
	@Override
	public void onResume() {
		super.onResume();
	}

	/**
	 * Checks to see if info exists for exhibit
	 */
	private void checkInfoURL() {
		// if url for information exists then true
		String testUrl = SITEURL + exhibitNum + "/info.html";
		URLCheckerAsync uA = new URLCheckerAsync(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				boolean answer = (Boolean) msg.obj;
				if (answer) {
					showInfoBtn();
				}

			}
		});
		uA.execute(testUrl);
	}

	/**
	 * Shows information button
	 */
	private void showInfoBtn() {
		btnInfo = (Button) findViewById(R.id.exhibitInfoButton);
		btnInfo.setVisibility(View.VISIBLE);
	}
	/**
	 * Checks to see if pictures exists for exhibit
	 */
	private void checkPicsURL() {
		// if url for pictures exists then true
		String testUrl = SITEURL + exhibitNum + "/pictures.html";
		Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				boolean answer = (Boolean) msg.obj;
				if (answer) {
					showPicsBtn();
				}

			}
		};
		URLCheckerAsync uA = new URLCheckerAsync(mHandler);
		uA.execute(testUrl);
	}

	/**
	 * Shows pictures button
	 */
	private void showPicsBtn() {
		btnPics = (Button) findViewById(R.id.exhibitPictureButton);
		btnPics.setVisibility(View.VISIBLE);
	}

	/**
	 * Checks to see if video exists for exhibit
	 */
	private void checkVideoURL() {
		// if url for pictures exists then true
		String testUrl = SITEURL + exhibitNum + "/video.mp4";
		Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				boolean answer = (Boolean) msg.obj;
				if (answer) {
					showVideoBtn();
				}

			}
		};
		URLCheckerAsync uA = new URLCheckerAsync(mHandler);
		uA.execute(testUrl);
	}

	/**
	 * Shows video button
	 */
	private void showVideoBtn() {
		btnVideo = (Button) findViewById(R.id.exhibitVideoButton);
		btnVideo.setVisibility(View.VISIBLE);
	}

	/**
	 * Checks to see if artifacts exist for exhibit
	 */
	private void checkArtifactsURL() {
		// if url for pictures exists then true
		String testUrl = SITEURL + exhibitNum + "/artifacts.html";
		Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				boolean answer = (Boolean) msg.obj;
				if (answer) {
					showArtifactBtn();
				}

			}
		};
		URLCheckerAsync uA = new URLCheckerAsync(mHandler);
		uA.execute(testUrl);
	}

	/**
	 * Shows artifact button
	 */
	private void showArtifactBtn() {
		btnArtifacts = (Button) findViewById(R.id.exhibitArtifactButton);
		btnArtifacts.setVisibility(View.VISIBLE);
	}

}